<template>
  <h3>表格合并测试</h3>



  <div id="wrap">
    <table>
      <tr class="mt-tr" v-for="rowData in tableData">
        <td v-for="cellData in rowData" ref="itemRefs" :id="cellData.id">
          <my-cell :cellValue="cellData.value"/>
        </td>
      </tr>
    </table>
  </div>

</template>

<script setup>

const tableData = (() => {
  let data = [];
  let num = 0;
  for (let i = 0; i < 10; i++) {
    let row = [];
    for (let j = 0; j < 8; j++) {
      let cell = {};
      cell.id = i + '' + j;
      cell.value = {
        num: num,
        text: i + '' + j,
      };
      num++;
      row.push(cell);
    }
    data.push(row);
  }
  return data;
})();


import {defineComponent, onMounted, ref, reactive} from 'vue';
import MyCell from "@/components/MyCell";

defineComponent({
  name: 'MyTable',
  components: {
    MyCell
  }
});

const arrToObj = (arr) => {
  return arr.reduce((obj, item) => {
    obj[item.id] = item;
    return obj;
  }, {})
};

const itemRefs = reactive([]);

onMounted(() => {
	const itemRefObj = arrToObj(itemRefs);
	cellMerge2(itemRefObj, 1, 2, 3, 5);
});

const cellMerge1 = () => {
  itemRefs[18].colSpan = 2;
  itemRefs[18].rowSpan = 2;
  itemRefs[19].style.display = 'none';
  itemRefs[26].style.display = 'none';
  itemRefs[27].style.display = 'none';
};

const cellMerge2 = (itemRefObj, rowIndex, colIndex, rowspan, colspan) => {

  if (rowIndex + rowspan > tableData.length || colIndex + colspan > tableData[0].length) {
    return;
  }

  let id = rowIndex + '' + colIndex;
  itemRefObj[id].colSpan = colspan;
  itemRefObj[id].rowSpan = rowspan;

  for (let i = rowIndex; i < rowIndex + rowspan; i++) {
    for (let j = colIndex; j < colIndex + colspan; j++) {
      let tdId = i + '' + j;
      if (tdId !== id) {
        itemRefObj[tdId].style.display = 'none';
      }
    }
  }
}

</script>

<style scoped>
#wrap {
  position: absolute;
  left: 300px;
  top: 100px;
}

table {
  border-collapse: collapse;
  border: 1px #C4C7CE solid;
}

th, td {
  padding: 0;
  width: 100px;
  border: 1px #C4C7CE solid;
  text-align: center;
}

#operButton {
  position: absolute;
  left: 600px;
  top: 100px;
}

#operButton button {
  width: 100px;
  height: 50px;
}
</style>
